package org.niux.AutoLoginQQ.operate;

import java.io.IOException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.widgets.Display;
import org.niux.AutoLoginQQ.VO.QQNumVO;
import org.niux.AutoLoginQQ.common.Constant;
import org.niux.AutoLoginQQ.ui.Main;
import org.niux.AutoLoginQQ.util.EncodeQQPass;

/**
 * 
 * Copyright (c) 2009,niux<br>
 * All rights reserved.<br>
 * 
 * 文件名称：ConfigDialog.java<br>
 * 摘 要：登录QQ操作类<br>
 * <br>
 * 当前版本：<br>
 * 作 者：mingxian Email: <a
 * href="mailto:liangmingxian@gmail.com">liangmingxian@gmail.com</a><br>
 * 完成日期：@since 2012-9-9<br>
 * <br>
 * 取代版本：<br>
 * 原作者 ：<br>
 * 完成日期：@since Oct 22, 2009<br>
 */
public class LoginQQ {

	private Log log = LogFactory.getLog(this.getClass());

	private Main gui;

	public LoginQQ(Main gui) {
		super();
		this.gui = gui;
	}

	/**
	 * 
	 * 方法概述：登录QQ
	 * 描述：登录QQ
	 * 
	 * @param qqList
	 * 返回类型：void 
	 * 修改人：梁铭显 修改时间：2012-9-11
	 */
	public void login(List<QQNumVO> qqList) {

		for (QQNumVO qq : qqList) {
			boolean isExist = false;

			List<QQNumVO> tempList = new ArrayList<QQNumVO>();
			
			tempList.addAll(Constant.LOGIN_QUEEN);
			
			for (QQNumVO qqInQueen : tempList) {// 判断选择的QQ是否已存在于等待队列中
				if (qqInQueen.getQqNum().equals(qq.getQqNum())) {
					log.debug("qq:" + qq.getQqNum() + "已经存在于队列当中");
					isExist = true;
					break;
				}
			}

			if (qq.isLogin()) {
				log.debug("qq:" + qq.getQqNum() + "已经登录");
				alert("QQ:" + qq.getQqNum() + "已经登录");
				isExist = true;
				break;
			}

			if (!isExist) { // 如果不存在就把QQ添加到队列当中
				if (Constant.QQ_LIST.get(qq.getQqNum()).getAlreadyLogin() != null) {
					if (qq.getAlreadyLogin() > Long
							.parseLong(Constant.LOGIN_TIME) * 60 * 1000) {
						log.debug("qq:" + qq.getQqNum() + "已经超过登录时间了");
//						alert("QQ:" + qq.getQqNum() + "已经超过登录时间了");
						continue;
					}
				}

				Constant.LOGIN_QUEEN.add(qq);

				updateWaitingLogin(Integer
						.toString(Constant.LOGIN_QUEEN.size()));
			}
		}
	}

	/**
	 * 
	 * 方法概述：登录QQ操作入口
	 *  描述：登录QQ操作入口
	 * 
	 * @param qqNum
	 * @param imageData
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-9
	 */
	public void loginQQ(List<QQNumVO> qqList) {
		for (int i = 0; i < qqList.size(); i++) {
			QQNumVO qqNumVO = qqList.get(i);

			if (!Constant.LOOP) {
				break;
			}

			if (qqNumVO.isLogin()) {
				continue;
			}

			log.debug("正在登录QQ：" + qqNumVO.getQqNum());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Constant.QQ_LIST.get(qqNumVO.getQqNum()).setLoginDate(sdf.format(new Date()));
			
			setSelectItem(qqNumVO.getIndex());
			updateOptStatus(qqNumVO.getIndex(), qqNumVO.getQqNum(), "正在登录...");
			Constant.LOGIN_COUNT++;

			// 创建默认的httpClient实例.
			HttpParams params = new BasicHttpParams();
			
			//连接超时 100秒
			params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Constant.TIMEOUT);
			
			//读取超时 100秒
			params.setParameter(CoreConnectionPNames.SO_TIMEOUT, Constant.TIMEOUT);
			
			params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
			
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

			SchemeRegistry schemeRegistry = new SchemeRegistry();

			// 连接方式
			schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
					.getSocketFactory()));
			
			//ssl
			try {
				SSLContext sslcontext = SSLContext.getInstance("SSL");
				sslcontext.init(null, new TrustManager[] { trustManager }, null);  
	            SSLSocketFactory sf = new SSLSocketFactory(sslcontext);  
//	            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
				schemeRegistry.register(new Scheme("https",443,sf));
			} catch (NoSuchAlgorithmException e1) {
				e1.printStackTrace();
			} catch (KeyManagementException e) {
				e.printStackTrace();
			}  

			PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);

			cm.setMaxTotal(Constant.MAX_CONNECTION);//最大连接数

			HttpClient httpclient = new DefaultHttpClient(cm, params);
			
			qqNumVO.setHttpClient(httpclient);
			
			// 从等待队列中移除
			Iterator<QQNumVO> waitLoginQueen = Constant.LOGIN_QUEEN.iterator();
			while (waitLoginQueen.hasNext()) {
				if (waitLoginQueen.next().getQqNum().equals(qqNumVO.getQqNum())) {
					log.debug("把QQ" + qqNumVO.getQqNum() + "从等待队列中移除");
					waitLoginQueen.remove();
				}
			}
			
			if (Constant.LOGIN_DATA.containsKey(qqNumVO.getQqNum())) {
				log.debug("可以免码登录");
				
				//创建新任务
				LoginTask task = new LoginTask(qqNumVO,gui,true);
				//添加新任务到线程池中
				Constant.THREAD_POOL_MANAGER.addTask(task);
				
				Constant.THREAD_POOL_MANAGER.getInfo();
				try {
					if(Integer.parseInt(Constant.DELAY_TIME) * 1000 > 300){
						Thread.sleep(Integer.parseInt(Constant.DELAY_TIME));
					} else {
						Thread.sleep(300);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				// 发送判断是否需要验证码的请求
				String responseString = checkVerifyCode(qqNumVO.getHttpClient(),
						qqNumVO.getQqNum());
				
				if(responseString == null || "null".equals(responseString)){
					log.debug(qqNumVO.getQqNum() + "查询是否需要验证码连接失败");
					updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "查询是否需要验证码时网络连接超时,请稍后重新登录");
					Constant.LOGIN_COUNT--; // 已登录个减1
					continue;
				}

				boolean isNeedVerifyCode = isNeedVerifyCode(responseString);

				log.debug(responseString);

				// 截取返回的第二个和第三个参数，密码加密用到
				String secondParam = responseString.split(",")[1].replace("'","");
				String thirdParam = responseString.split(",")[2].replace("'", "").replace(")", "").replace(";", "");

				if (isNeedVerifyCode&& Constant.IS_LOGIN_NEED_VERIFYCODE.equals("true")) { // 登录需要验证码的QQ
					log.debug("获取验证码");
					updateOptStatus(qqNumVO.getIndex(), qqNumVO.getQqNum(),"正在获取验证码..."); // 更新界面表格
					ImageData verifyCodeImage = getVerifyCode(qqNumVO.getHttpClient(),qqNumVO.getQqNum());
					
					if(verifyCodeImage == null){
						log.debug(qqNumVO.getQqNum() + "获取验证码连接失败");
						updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "获取验证码时连接超时,请稍后重新登录");
						Constant.LOGIN_COUNT--; // 已登录个减1
						continue;
					}

					// 打开验证码输入框
					showVerifyCode(qqNumVO.getQqNum(), verifyCodeImage);
					
					// 等待用户输入
					while (Constant.VERIFYCODE == null) {
						// 空循环等待输入
					}

					verifyCodeImage = null;
					
					if ("".equals(Constant.VERIFYCODE)) {
						updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "没有输入验证码"); // 更新界面表格
						Constant.LOGIN_COUNT--; // 已登录个减1
						Constant.VERIFYCODE = null;
						continue;
					}

					secondParam = Constant.VERIFYCODE;

					log.debug("输入的验证码是：" + Constant.VERIFYCODE);
				} else if (isNeedVerifyCode
						&& Constant.IS_LOGIN_NEED_VERIFYCODE.equals("false")) { // 不登录需要验证码的QQ
					log.debug("获取验证码,跳过");
					updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "需要验证码，跳过登录"); // 更新界面表格
					Constant.VERIFYCODE = null;
					Constant.LOGIN_COUNT--; // 已登录个减1
					
					// 登录延时
					try {
						Thread.sleep(Long.parseLong(Constant.DELAY_TIME) * 1000);
					} catch (Exception e) {
						e.printStackTrace();
					}

					continue;
				}
				
				updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "正在执行第一次登录");
				
				responseString = firstLogin(qqNumVO.getHttpClient(), qqNumVO, secondParam,thirdParam);
				
				if(responseString == null || "null".equals(responseString)){
					log.debug(qqNumVO.getQqNum() + "执行第一次登录时连接失败");
					updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "执行第一次登录时网络连接超时，请稍后重新登录");
					Constant.LOGIN_COUNT--; // 已登录个减1
					continue;
				}

				log.debug(qqNumVO.getQqNum() + "执行第一次登录请求的返回：" + responseString);

				// 帐号被冻洁
				if (responseString.contains("http://aq.qq.com/")) {
					updateStatus(qqNumVO.getIndex(), qqNumVO.getQqNum(),"需要激活，限制登录"); // 更新界面表格
					updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "需要激活，限制登录"); // 更新界面表格
					Constant.LOGIN_COUNT--; // 已登录个数减1
					Constant.VERIFYCODE = null;

					updateWaitingLogin(Integer.toString(Constant.LOGIN_QUEEN
							.size()));

					updateFailCount();

					// 登录延时
					try {
						Thread.sleep(Long.parseLong(Constant.DELAY_TIME) * 1000);
					} catch (Exception e) {
						e.printStackTrace();
					}

					continue;
				}

				// 判断登录状况并更新界面表格
				if (responseString.contains("ptuiCB('0'")) { // 登录成功
					/**
					 * 2013-8-12，腾讯协议修改版本
					 */
					//访问跳转的URL以获得新的COOKIES
					
					//获取跳转URL
					String jumpUrl = responseString.split(",")[2].replace("'", "");
					
					HttpGet httpget = new HttpGet(jumpUrl);

					// 设置http头信息
					httpget.setHeader("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash," +
							" application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*");
					httpget.setHeader("Accept-Encoding", "gzip, deflate");
					httpget.setHeader("Accept-Language", "en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3");
					httpget.setHeader("Connection", "Keep-Alive");
					httpget.setHeader("Host", "ssl.ptlogin2.qq.com");
					httpget.setHeader("Referer","https://ui.ptlogin2.qq.com/cgi-bin/login?daid=164&target=self&style=5&mibao_css=m_webqq" +
							"&appid=1003903&enable_qlogin=0&no_verifyimg=1&s_url=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html" +
							"&f_url=loginerroralert&strong_login=1&login_state=10&t="+ getUTCTime());
					httpget.setHeader("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");

					try {
						HttpResponse response = httpclient.execute(httpget);

						// 获取cookies
						List<Cookie> cookies = ((AbstractHttpClient) httpclient).getCookieStore().getCookies();

						// 从cookies中获取ptwebqq的值
						for (int j = 0; j < cookies.size(); j++) {
							log.debug(cookies.get(j).getName() + "=" + cookies.get(j).getValue());
						}
									
						// 获取响应实
						HttpEntity entity = response.getEntity();

						responseString = EntityUtils.toString(entity);

						log.debug(responseString);
					} catch (Exception e) {
						log.error(qqNumVO.getQqNum() + "网络连接超时",e);
						e.printStackTrace();
						httpget.abort();
						httpget.releaseConnection();
						Constant.QQ_LIST.get(qqNumVO.getQqNum()).getHttpClient().getConnectionManager().shutdown();
					}
					
					/**
					 * 2013-8-12，腾讯协议修改版本
					 */
					//访问跳转的URL以获得新的COOKIES
					httpget = new HttpGet("http://ptlogin4.web2.qq.com/check_sig?pttype=1&" +
							"uin="+qqNumVO.getQqNum()+"&service=login&nodirect=0&ptsig=xyYGKsSkZkcbtTIh1UgFiLHDBIWqsmtcxX*gFpkhAXY_&" +
							"s_url=http%3a%2f%2fweb2.qq.com%2floginproxy.html%3flogin2qq%3d1%26webqq%5ftype%3d10&" +
							"f_url=&ptlang=2052&ptredirect=100&aid=1003903&daid=164&j_later=0&low_login_hour=0&regmaster=0");

					// 设置http头信息
					httpget.setHeader("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash," +
							" application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*");
					httpget.setHeader("Accept-Encoding", "gzip, deflate");
					httpget.setHeader("Accept-Language", "en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3");
					httpget.setHeader("Connection", "Keep-Alive");
					httpget.setHeader("Host", "ptlogin4.web2.qq.com");
					httpget.setHeader("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");

					try {
						HttpResponse response = httpclient.execute(httpget);

						// 获取cookies
						List<Cookie> cookies = ((AbstractHttpClient) httpclient).getCookieStore().getCookies();

						// 从cookies中获取ptwebqq的值
						for (int j = 0; j < cookies.size(); j++) {
							log.debug(cookies.get(j).getName() + "=" + cookies.get(j).getValue());
						}
									
						// 获取响应实
						HttpEntity entity = response.getEntity();

						responseString = EntityUtils.toString(entity);

						log.debug(responseString);
					} catch (Exception e) {
						log.error(qqNumVO.getQqNum() + "网络连接超时",e);
						e.printStackTrace();
						httpget.abort();
						httpget.releaseConnection();
						Constant.QQ_LIST.get(qqNumVO.getQqNum()).getHttpClient().getConnectionManager().shutdown();
					}
					
					//创建新任务
					LoginTask task = new LoginTask(qqNumVO,gui,false);
					//添加新任务到线程池中
					Constant.THREAD_POOL_MANAGER.addTask(task);
					
					Constant.THREAD_POOL_MANAGER.getInfo();
				} else if (responseString.contains("ptuiCB('3'")) { // 密码错误
					updateStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "QQ密码错误"); // 更新界面表格
					updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "QQ密码错误"); // 更新界面表格
					Constant.LOGIN_COUNT--; // 已登录个数减1

					updateWaitingLogin(Integer.toString(Constant.LOGIN_QUEEN
							.size()));

					updateWrongPassword();

				} else if (responseString.contains("ptuiCB('4'")) { // 验证码输入错误
					updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "验证码输入错误"); // 更新界面表格
					i--;
					Constant.LOGIN_COUNT--; // 已登录个数减1
				} else if (responseString.contains("ptuiCB('7'")) { // 网络连接异常,可能是没输入验证码
					updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "网络连接异常"); // 更新界面表格
					Constant.LOGIN_COUNT--; // 已登录个数减1

					updateWaitingLogin(Integer.toString(Constant.LOGIN_QUEEN
							.size()));

					updateFailCount();

				} else if (responseString.contains("ptuiCB('19'")) { // 您的号码已暂时被登录限制
					updateStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "号码已暂时被限制登录"); // 更新界面表格
					updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "号码已暂时被限制登录"); // 更新界面表格
					Constant.LOGIN_COUNT--; // 已登录个数减1

					updateWaitingLogin(Integer.toString(Constant.LOGIN_QUEEN
							.size()));

					updateFailCount();
				}
			}
			
			Constant.VERIFYCODE = null;

			// 登录延时
			try {
				Thread.sleep(Long.parseLong(Constant.DELAY_TIME) * 1000);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 
	 * 方法概述：发送请求判断是否需要验证码 
	 * 描述：发送请求判断是否需要验证码
	 * 
	 * @param httpclient
	 * @param qqNum
	 * @return 
	 * 返回类型：String 
	 * 修改人：梁铭显
	 * 修改时间：2012-9-9
	 */
	public String checkVerifyCode(HttpClient httpclient, String qqNum) {

		log.debug("发送判断是否需要验证码的请求");

		// 创建httpget.
//		HttpGet httpget = new HttpGet("http://check.ptlogin2.qq.com/check?uin="
//				+ qqNum + "&appid=1003903&r=0.9982102437527717");
		
		/**
		 * 新协议2013-08-11
		 */
		HttpGet httpget = new HttpGet("https://ssl.ptlogin2.qq.com/check?uin="
						+ qqNum + "&appid=1003903&js_ver=10039&js_type=0&" +
						"login_sig=9ngYXi7xzebsm6kd18I4*tQJJ4qwZB9Vl9fuIg8ZoTVq5hU5ciO1hImp3D1dsDBl&" +
						"u1=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html&r=0.30686489124400023");

		// 设置http头信息
		httpget.setHeader("Accept", "*/*");
		httpget.setHeader("Accept-Encoding", "gzip, deflate");
		httpget.setHeader("Referer", "https://ui.ptlogin2.qq.com/cgi-bin/login?daid=164&target=self&" +
				"style=5&mibao_css=m_webqq&appid=1003903&enable_qlogin=0&no_verifyimg=1&" +
				"s_url=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html&f_url=loginerroralert&strong_login=1&" +
				"login_state=10&t=20130723001");
		httpget.setHeader("Accept-Language", "zh-cn");
		httpget.setHeader("Connection", "Keep-Alive");
		
		/**
		 * 新协议2013-08-11
		 */
		httpget.setHeader("Host", "ssl.ptlogin2.qq.com");
		httpget.setHeader("User-Agent",
				"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
					
		log.debug("不能免码登录，重新设置Cookies");
		// 设置Cookies
		/**
		 * 新协议2013-08-11
		 */
		BasicClientCookie chkuin = new BasicClientCookie("chkuin", qqNum);
		BasicClientCookie pgv_info = new BasicClientCookie("pgv_info","pgvReferrer=&ssid=s63431060");
		BasicClientCookie pgv_pvid = new BasicClientCookie("pgv_pvid","5159513870");
		BasicClientCookie uikey = new BasicClientCookie("uikey", "4b4df30eefbe10986c43f41255a088a26e6b69e305a55304d407ef0bfa23cf68");
		
		((AbstractHttpClient) httpclient).getCookieStore().addCookie(chkuin);
		((AbstractHttpClient) httpclient).getCookieStore().addCookie(pgv_info);
		((AbstractHttpClient) httpclient).getCookieStore().addCookie(pgv_pvid);
		((AbstractHttpClient) httpclient).getCookieStore().addCookie(uikey);

		String responseString = "";

		try {
			HttpResponse response = httpclient.execute(httpget);

			// 获取响应实
			HttpEntity entity = response.getEntity();

			responseString = EntityUtils.toString(entity);
			
			// 获取cookies
			List<Cookie> cookies = ((AbstractHttpClient) httpclient).getCookieStore().getCookies();

			// 从cookies中获取ptwebqq的值
			for (int i = 0; i < cookies.size(); i++) {
				log.debug(cookies.get(i).getName() + "=" + cookies.get(i).getValue());
			}
			
			return responseString;
		} catch (Exception e) {
			log.debug(qqNum + "网络连接超时");
			e.printStackTrace();
			httpget.abort();
			httpget.releaseConnection();
			Constant.QQ_LIST.get(qqNum).getHttpClient().getConnectionManager().shutdown();
			return null;
		}
	}

	/**
	 * 
	 * 方法概述：判断是否需要验证码 
	 * 描述：判断是否需要验证码
	 * 
	 * @param responseString
	 * @return 
	 * 返回类型：boolean 
	 * 修改人：梁铭显
	 * 修改时间：2012-9-9
	 */
	public boolean isNeedVerifyCode(String responseString) {
		log.debug("判断是否需要验证码");
		// 判断是否需要验证码
		// ptui_checkVC('0','!8Z3','\x00\x00\x00\x00\x18\xc4\x46\x0e');这种返回格式是不需要验证码
		// ptui_checkVC('1','6eca383c5c31537b6dbb2258ea5cc9bf49ab51677128db2b','\x00\x00\x00\x00\x01\xf0\xbb\xec');
		// 这种返回格式需要验证码
		if (responseString.contains("ptui_checkVC('0'")) {// 不需要验证码
			log.debug("不需要验证码");
			return false;
		} else { // 需要验证码
			log.debug("需要验证码");
			return true;
		}
	}

	/**
	 * 
	 * 方法概述：获取验证码图片数据
	 * 描述：获取验证码图片数据
	 * 
	 * @param httpclient
	 * @param qqNum
	 * @return 
	 * 返回类型：ImageData 
	 * 修改人：梁铭显  
	 * 修改时间：2012-9-9
	 */
	public ImageData getVerifyCode(HttpClient httpclient, String qqNum) {

		log.debug("获取验证码图片数据");

//		HttpGet httpget = new HttpGet(
//				"http://captcha.qq.com/getimage?aid=1003903&r=0.3980147237574003&uin="
//						+ qqNum);
		
		/**
		 * 新协议2013-08-11
		 */
		HttpGet httpget = new HttpGet("https://ssl.captcha.qq.com/getimage?aid=1003903&r=0.29858012050202553&uin=" + qqNum);

		// 设置http头信息
//		httpget.setHeader("Accept", "application/javascript, */*;q=0.8");
		httpget.setHeader("Accept", "image/png, image/svg+xml, image/*;q=0.8, */*;q=0.5");
		httpget.setHeader("Accept-Encoding", "gzip, deflate");
//		httpget.setHeader("Accept-Language", "zh-cn");
		httpget.setHeader("Accept-Language", "en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3");
		httpget.setHeader("Connection", "Keep-Alive");
//		httpget.setHeader("Host", "captcha.qq.com");
		httpget.setHeader("Host", "ssl.captcha.qq.com");
		httpget.setHeader("User-Agent",
				"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");

		ImageData[] imageDatas = null;

		try {
			HttpResponse response = httpclient.execute(httpget);

			// 获取响应实
			HttpEntity entity = response.getEntity();

			// 构建验证码图片
			ImageLoader loader = new ImageLoader();
			imageDatas = loader.load(entity.getContent());

			return imageDatas[0];
		} catch (Exception e) {
			log.error("网络连接超时", e);
			e.printStackTrace();
			httpget.abort();
			httpget.releaseConnection();
			Constant.QQ_LIST.get(qqNum).getHttpClient().getConnectionManager().shutdown();
			return null;
		}
	}

	/**
	 * 
	 * 方法概述：第一次登录操作 
	 * 描述：第一次登录操作
	 * 
	 * @param HttpClient httpclient
	 * @param QQNumVO qq
	 * @param String verifycode
	 * @param String encodeKey
	 * @return 
	 * 返回类型：ImageData 
	 * 修改人：梁铭显  
	 * 修改时间：2012-9-9
	 */
	@SuppressWarnings("static-access")
	public String firstLogin(HttpClient httpclient, QQNumVO qq,
			String verifycode, String encodeKey) {
		log.debug("第一次登录操作");

		// 加密QQ密码
		EncodeQQPass encodeQQPass = new EncodeQQPass();

		String p = encodeQQPass.encodePass(qq.getPassword(), verifycode,
				encodeKey);

		HttpGet httpget = new HttpGet(
				"https://ssl.ptlogin2.qq.com/login?u="
						+ qq.getQqNum()
						+ "&p="
						+ p
						+ "&"
						+ "verifycode="
						+ verifycode
						+ "&webqq_type=10&remember_uin=1&login2qq=1&aid=1003903&u1=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html"
						+ "%3Flogin2qq%3D1%26webqq_type%3D10&h=1&ptredirect=0&ptlang=2052&daid=164&from_ui=1&pttype=1&dumy=&fp=loginerroralert"
						+ "&action=2-27-31245&mibao_css=m_webqq&t=1&g=1&js_type=0&js_ver=10039" 
						+ "&login_sig=dDPpv0kQL4SVGybZZS2r2qCsDUPaFalxhwGO4eVmKRWMR6scoNUqeJCSpznuXDEN");

		// 设置http头信息
		httpget.setHeader("Accept", "application/javascript, */*;q=0.8");
		httpget.setHeader("Accept-Encoding", "gzip, deflate");
		httpget.setHeader("Accept-Language", "en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3");
		httpget.setHeader("Connection", "Keep-Alive");
		httpget.setHeader("Host", "ssl.ptlogin2.qq.com");
		httpget.setHeader(
				"Referer",
				"https://ui.ptlogin2.qq.com/cgi-bin/login?daid=164&target=self&style=5"
						+ "&mibao_css=m_webqq&appid=1003903&enable_qlogin=0&no_verifyimg=1&"
						+ "s_url=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html&f_url=loginerroralert&strong_login=1&login_state=10&t="
						+ getUTCTime());
		httpget.setHeader("User-Agent",
				"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");

		String responseString = "";

		try {
			HttpResponse response = httpclient.execute(httpget);

			// 获取cookies
						List<Cookie> cookies = ((AbstractHttpClient) httpclient).getCookieStore().getCookies();

						// 从cookies中获取ptwebqq的值
						for (int i = 0; i < cookies.size(); i++) {
							log.debug(cookies.get(i).getName() + "=" + cookies.get(i).getValue());
						}
						
			// 获取响应实
			HttpEntity entity = response.getEntity();

			responseString = EntityUtils.toString(entity);

			return responseString;
		} catch (Exception e) {
			log.error(qq.getQqNum() + "网络连接超时",e);
			e.printStackTrace();
			httpget.abort();
			httpget.releaseConnection();
			Constant.QQ_LIST.get(qq.getQqNum()).getHttpClient().getConnectionManager().shutdown();
			return null;
		}
	}

	/**
	 * 
	 * 方法概述：第二次登录 
	 * 描述：第二次登录
	 * 
	 * @param httpclient
	 * @param qq
	 * @return 
	 * 返回类型：String 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-10
	 */
	@SuppressWarnings("deprecation")
	public String secondLogin(HttpClient httpclient, QQNumVO qq,boolean canNoVerify) {

		log.debug("第二次登录操作");
		
		updateOptStatus(qq.getIndex(),qq.getQqNum(), "正在执行第二次登录");

		HttpPost httppost = new HttpPost("http://d.web2.qq.com/channel/login2");

		// 设置http头信息
		httppost.setHeader("Accept", "*/*");
		httppost.setHeader("Accept-Encoding", "gzip,deflate,sdch");
		httppost.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
//		httppost.setHeader("Cache-Control", "no-cache");
		httppost.setHeader("Connection", "Keep-Alive");
		httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
		httppost.setHeader("Host", "d.web2.qq.com");
		httppost.setHeader("Referer",
				"http://d.web2.qq.com/proxy.html?v=20110331002&callback=1&id=2"); // 一定要这一个，如果不是会出现103错误
		httppost.setHeader("User-Agent",
				"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");

		String ptwebqq = "";

		if (canNoVerify) {
			log.debug("设置成功登录的Cookies数据");
			List<Cookie> cookies = Constant.LOGIN_DATA.get(qq.getQqNum());

			// 从cookies中获取ptwebqq的值
			for (int i = 0; i < cookies.size(); i++) {
				if (cookies.get(i).getName().equals("ptwebqq")) {
					ptwebqq = cookies.get(i).getValue();
				}
			}

			for (Cookie cookie : cookies) {
				((AbstractHttpClient) httpclient).getCookieStore().addCookie(
						cookie);
			}
		} else {
			// 获取cookies
			List<Cookie> cookies = ((AbstractHttpClient) httpclient)
					.getCookieStore().getCookies();

			// 从cookies中获取ptwebqq的值
			for (int i = 0; i < cookies.size(); i++) {
				if (cookies.get(i).getName().equals("ptwebqq")) {
					ptwebqq = cookies.get(i).getValue();
				}
			}
//
//			// 清空cookies
//			((AbstractHttpClient) httpclient).getCookieStore().clear();
//
//			for (int i = 0; i < cookies.size(); i++) {
//				log.debug(cookies.get(i).getName() + "========" + cookies.get(i).getValue());
//				if (cookies.get(i).getName().equals("ac")) {
//					((AbstractHttpClient) httpclient).getCookieStore()
//							.addCookie(cookies.get(i));
//				} else if (cookies.get(i).getName().equals("euin_cookie")) {
//					((AbstractHttpClient) httpclient).getCookieStore()
//							.addCookie(cookies.get(i));
//				} else if (cookies.get(i).getName().equals("confirmuin")) {
//					((AbstractHttpClient) httpclient).getCookieStore()
//							.addCookie(cookies.get(i));
//				} else if (cookies.get(i).getName().equals("verifysession")) {
//					((AbstractHttpClient) httpclient).getCookieStore()
//							.addCookie(cookies.get(i));
//				} else if (cookies.get(i).getName().equals("o_cookie")) {
//					((AbstractHttpClient) httpclient).getCookieStore()
//							.addCookie(cookies.get(i));
//				} else if (cookies.get(i).getName().equals("pgv_info")) {
//					((AbstractHttpClient) httpclient).getCookieStore()
//							.addCookie(cookies.get(i));
//				} else if (cookies.get(i).getName().equals("pgv_pvid")) {
//					((AbstractHttpClient) httpclient).getCookieStore()
//							.addCookie(cookies.get(i));
//				} else if (cookies.get(i).getName().equals("pt2gguin")) {
//					((AbstractHttpClient) httpclient).getCookieStore()
//							.addCookie(cookies.get(i));
//				} else if (cookies.get(i).getName().equals("ptisp")) {
//					((AbstractHttpClient) httpclient).getCookieStore()
//							.addCookie(cookies.get(i));
//				} else if (cookies.get(i).getName().equals("ptwebqq")) {
//					((AbstractHttpClient) httpclient).getCookieStore()
//							.addCookie(cookies.get(i));
//				} else if (cookies.get(i).getName().equals("RK")) {
//					((AbstractHttpClient) httpclient).getCookieStore()
//							.addCookie(cookies.get(i));
//				} else if (cookies.get(i).getName().equals("skey")) {
//					((AbstractHttpClient) httpclient).getCookieStore()
//							.addCookie(cookies.get(i));
//				} else if (cookies.get(i).getName().equals("uin")) {
//					((AbstractHttpClient) httpclient).getCookieStore()
//							.addCookie(cookies.get(i));
//				} else if (cookies.get(i).getName().equals("uin_cookie")) {
//					((AbstractHttpClient) httpclient).getCookieStore()
//							.addCookie(cookies.get(i));
//				}
//			}

//			BasicClientCookie ptui_loginuin = new BasicClientCookie(
//					"ptui_loginuin", qq.getQqNum());
//			ptui_loginuin.setDomain("qq.com");
//			ptui_loginuin.setPath("/");
//
//			((AbstractHttpClient) httpclient).getCookieStore().addCookie(
//					ptui_loginuin);
		}

		String param = "{\"status\":\""
				+ Constant.LOGIN_STATUS
				+ "\",\"ptwebqq\":\""
				+ ptwebqq
				+ "\","
				+ "\"passwd_sig\":\"\",\"clientid\":\"50705043\",\"psessionid\":null}";

		String encode = URLEncoder.encode(param);

		String responseString = "";
		try {
			StringEntity stringEntity = new StringEntity("r=" + encode
					+ "&clientid=50705043&psessionid=null");
			stringEntity.setContentType("application/x-www-form-urlencoded");

			httppost.setEntity(stringEntity);

			log.debug(qq.getQqNum() + "第二次登录请求发送");
			HttpResponse response = httpclient.execute(httppost);

			// 获取响应实
			HttpEntity entity = response.getEntity();
			log.debug(qq.getQqNum() + "第二次登录请求返回");

			responseString = EntityUtils.toString(entity);
			
			log.debug(responseString);
			
			if(canNoVerify && responseString.contains("retcode\":100000")){
				log.debug("Cookies过期，重新登录");
				updateOptStatus(qq.getIndex(),qq.getQqNum(), "Cookies过期，重新登录"); // 更新界面表格
				Constant.LOGIN_DATA.remove(qq.getQqNum());
				return "cookies";
			} else if(canNoVerify && responseString.contains("retcode\":103")){
				log.debug("掉线，重新登录");
				updateOptStatus(qq.getIndex(),qq.getQqNum(), "掉线，重新登录"); // 更新界面表格
				Constant.LOGIN_DATA.remove(qq.getQqNum());
				return "cookies";
			} else {
				log.debug("登录成功，保存登录数据");
				updateOptStatus(qq.getIndex(),qq.getQqNum(), "登录成功"); // 更新界面表格
				Constant.LOGIN_DATA.remove(qq.getQqNum());
				
				List<Cookie> cookies = ((AbstractHttpClient) httpclient).getCookieStore().getCookies();
				Constant.LOGIN_DATA.put(qq.getQqNum(), cookies);
				return responseString;
			}
		} catch (Exception e) {
			log.error(qq.getQqNum() + "网络连接超时",e);
			e.printStackTrace();
			httppost.abort();
			httppost.releaseConnection();
			Constant.QQ_LIST.get(qq.getQqNum()).getHttpClient().getConnectionManager().shutdown();
			return null;
		}
	}

	/**
	 * 
	 * 方法概述：获取QQ用户信息 
	 * 描述：获取QQ用户信息
	 * 
	 * @param httpclient
	 * @param qq
	 * @param vfwebqq
	 * @return 
	 * 返回类型：String 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-14
	 */
	public String getUserInfo(HttpClient httpclient, QQNumVO qq, String vfwebqq) {
		log.debug("获取用户信息");
		
//		updateOptStatus(qq.getIndex(), "获取用户信息");
		
		HttpGet httpget = new HttpGet(
				"http://s.web2.qq.com/api/get_friend_info2?tuin="
						+ qq.getQqNum() + "&verifysession=&code=&" + "vfwebqq="
						+ vfwebqq + "&t=" + getUTCTime());

		// 设置http头信息
		httpget.setHeader("Accept", "*/*");
		httpget.setHeader("Accept-Encoding", "gzip, deflate");
		httpget.setHeader("Accept-Language", "zh-cn");
		httpget.setHeader("Connection", "Keep-Alive");
		httpget.setHeader("Content-Type", "utf-8");
		httpget.setHeader("Host", "s.web2.qq.com");
		httpget.setHeader("Referer",
				"http://s.web2.qq.com/proxy.html?v=20110331002&callback=1&id=2");
		httpget.setHeader("User-Agent",
				"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");

		String responseString = "";

		try {
			HttpResponse response = httpclient.execute(httpget);

			// 获取响应实
			HttpEntity entity = response.getEntity();

			responseString = EntityUtils.toString(entity);

			return responseString;
		} catch (Exception e) {
			log.error("网络连接超时",e);
			e.printStackTrace();
			httpget.abort();
			httpget.releaseConnection();
			return null;
		}
	}

	/**
	 * 
	 * 方法概述：获取QQ个性签名 
	 * 描述：获取QQ个性签名
	 * 
	 * @param httpclient
	 * @param qq
	 * @param vfwebqq
	 * @return 
	 * 返回类型：String 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-14
	 */
	public String getSingleLongNick(HttpClient httpclient, QQNumVO qq,
			String vfwebqq) {
		log.debug("获取个性签名");
//		updateOptStatus(qq.getIndex(), "获取个性签名");
		
		HttpGet httpget = new HttpGet(
				"http://s.web2.qq.com/api/get_single_long_nick2?tuin="
						+ qq.getQqNum() + "&vfwebqq=" + vfwebqq + "&t="
						+ getUTCTime());

		// 设置http头信息
		httpget.setHeader("Accept", "*/*");
		httpget.setHeader("Accept-Encoding", "gzip, deflate");
		httpget.setHeader("Accept-Language", "zh-cn");
		httpget.setHeader("Connection", "Keep-Alive");
		httpget.setHeader("Content-Type", "utf-8");
		httpget.setHeader("Host", "s.web2.qq.com");
		httpget.setHeader("Referer",
				"http://s.web2.qq.com/proxy.html?v=20110331002&callback=1&id=3");
		httpget.setHeader("User-Agent",
				"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");

		String responseString = "";

		try {
			HttpResponse response = httpclient.execute(httpget);

			// 获取响应实
			HttpEntity entity = response.getEntity();

			responseString = EntityUtils.toString(entity);

			return responseString;
		} catch (IOException e) {
			log.error("网络连接超时", e);
			e.printStackTrace();
			httpget.abort();
			httpget.releaseConnection();
			return null;
		}
	}

	/**
	 * 
	 * 方法概述：获取QQ等级信息 
	 * 描述：获取QQ等级信息
	 * 
	 * @param httpclient
	 * @param qq
	 * @param vfwebqq
	 * @return 
	 * 返回类型：String 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-10
	 */
	public String getLevel(HttpClient httpclient, QQNumVO qq, String vfwebqq) {

		log.debug("获取等级信息");
//		updateOptStatus(qq.getIndex(), "获取等级信息");
		
		HttpGet httpget = new HttpGet(
				"http://s.web2.qq.com/api/get_qq_level2?tuin=" + qq.getQqNum()
						+ "&" + "vfwebqq=" + vfwebqq + "&t=" + getUTCTime());

		// 设置http头信息
		httpget.setHeader("Accept", "*/*");
		httpget.setHeader("Accept-Encoding", "gzip, deflate");
		httpget.setHeader("Accept-Language", "zh-cn");
		httpget.setHeader("Connection", "Keep-Alive");
		httpget.setHeader("Content-Type", "utf-8");
		httpget.setHeader("Host", "s.web2.qq.com");
		httpget.setHeader("Referer",
				"http://s.web2.qq.com/proxy.html?v=20110331002&callback=1&id=2");
		httpget.setHeader("User-Agent",
				"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");

		String responseString = "";

		try {
			HttpResponse response = httpclient.execute(httpget);

			// 获取响应实
			HttpEntity entity = response.getEntity();

			responseString = EntityUtils.toString(entity);

			return responseString;
			
		} catch (Exception e) {
			log.error("网络连接超时", e);
			e.printStackTrace();
			httpget.abort();
			httpget.releaseConnection();
			return null;
		}
	}

	/**
	 * 
	 * 方法概述：发送心跳包请求
	 * 描述：发送心跳包请求
	 * 
	 * @param httpclient
	 * @param psessionid
	 * @param qq
	 * @return 
	 * 返回类型： 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-10
	 */
	public void sentPoll(HttpClient httpclient, String psessionid,
			QQNumVO qq) {
		// 发送心跳包
		if (!Constant.QQ_LIST.get(qq.getQqNum()).isLogin()) {
			log.debug(qq.getQqNum() + "已退出登录");
			return;
		}
		
		log.debug("创建"+qq.getQqNum()+"的心跳包发送任务");
		//创建新任务
		SendPollTask task = new SendPollTask(qq,gui,psessionid);
		//添加新任务到线程池中
		Constant.THREAD_POOL_MANAGER.addSendPollTask(task);
				
		Constant.THREAD_POOL_MANAGER.getInfo();
//		Thread t = new Thread(new Runnable() {
//			public void run() {
//				
//			}
//		});
//
//		t.start();
//
//		Constant.THREAD_POOL.add(t);
	}

	/**
	 * 
	 * 方法概述：掉线重新登录 
	 * 描述：掉线重新登录
	 * 
	 * @param httpclient
	 * @param qqNumVO
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-10
	 */
	public void reLogin(HttpClient httpclient, QQNumVO qqNumVO) {

//		if (!Constant.QQ_LIST.get(qqNumVO.getQqNum()).isLogin()) {
//			return;
//		}

		// 从等待队列中移除
		Iterator<QQNumVO> waitLoginQueen = Constant.LOGIN_QUEEN.iterator();
			while (waitLoginQueen.hasNext()) {
				if (waitLoginQueen.next().getQqNum().equals(qqNumVO.getQqNum())) {
					log.debug("把QQ" + qqNumVO.getQqNum() + "从等待队列中移除");
					waitLoginQueen.remove();
				}
		}
		
		//创建新任务
		LoginTask task = new LoginTask(qqNumVO,gui,true);
		//添加新任务到线程池中
		Constant.THREAD_POOL_MANAGER.addTask(task);
		
		Constant.THREAD_POOL_MANAGER.getInfo();
//		
//		String responseString = secondLogin(httpclient, qqNumVO, true);
//		
//		if(responseString == null){
//			updateOptStatus(qqNumVO.getIndex(), "网络连接超时");
//			
//			Iterator<QQNumVO> i = Constant.ALREADY_LOGIN_QUEEN.iterator();
//
//			while (i.hasNext()) {
//				if (i.next().getQqNum().equals(qqNumVO.getQqNum())) {
//					i.remove();
//				}
//			}
//			
//			return;
//		} else if (responseString.contains("{\"retcode\":103")
//				|| responseString.contains("{\"retcode\":108")
//				|| responseString.contains("{\"retcode\":114")
//				|| responseString.contains("{\"retcode\":121")) {
//			
//			updateOptStatus(qqNumVO.getIndex(), "自动重登失败，请手动登录");
//			updateStatus(qqNumVO.getIndex(), "掉线");
//			
//			Iterator<QQNumVO> i = Constant.ALREADY_LOGIN_QUEEN.iterator();
//
//			while (i.hasNext()) {
//				if (i.next().getQqNum().equals(qqNumVO.getQqNum())) {
//					i.remove();
//				}
//			}
//			
//			return;
//		}
//
//		log.debug(qqNumVO.getQqNum() + "重登反回" + responseString);
//
//		JSONObject responseJson = JSONObject.fromObject(responseString); // 由JSON转成JSONOBJECT对象
//
//		JSONObject resultForJson = JSONObject.fromObject(responseJson
//				.get("result")); // 获取result部份
//
//		String status = resultForJson.getString("status");
//		String vfwebqq = resultForJson.getString("vfwebqq");
//		String psessionid = resultForJson.getString("psessionid");
//
//		// 更新QQ在线状态
//		if (status.equals("online")) {
//			updateStatus(qqNumVO.getIndex(), "在线"); // 更新界面表格
//		} else if (status.equals("callme")) {
//			updateStatus(qqNumVO.getIndex(), "Q我吧"); // 更新界面表格
//		} else if (status.equals("away")) {
//			updateStatus(qqNumVO.getIndex(), "离开"); // 更新界面表格
//		} else if (status.equals("busy")) {
//			updateStatus(qqNumVO.getIndex(), "忙碌"); // 更新界面表格
//		} else if (status.equals("silent")) {
//			updateStatus(qqNumVO.getIndex(), "请勿打扰"); // 更新界面表格
//		} else if (status.equals("hidden")) {
//			updateStatus(qqNumVO.getIndex(), "隐身"); // 更新界面表格
//		} else if (status.equals("offline")) {
//			updateStatus(qqNumVO.getIndex(), "离线"); // 更新界面表格
//		}
//
//		// 获取等级信息
//		responseString = getLevel(httpclient, qqNumVO, vfwebqq);
//
//		responseJson = JSONObject.fromObject(responseString); // 由JSON转成JSONOBJECT对象
//		resultForJson = JSONObject.fromObject(responseJson.get("result")); // 获取result部份
//
//		String level = resultForJson.getString("level");
//		String days = resultForJson.getString("days");
//		String remainDays = resultForJson.getString("remainDays");
//
//		// 更新等级信息
//		updateLevelInfo(qqNumVO.getIndex(), level, days, remainDays);
//
//		// 获取QQ用户信息
//		responseString = getUserInfo(httpclient, qqNumVO, vfwebqq);
//
//		responseJson = JSONObject.fromObject(responseString); // 由JSON转成JSONOBJECT对象
//		resultForJson = JSONObject.fromObject(responseJson.get("result")); // 获取result部份
//
//		String nick = resultForJson.getString("nick");
//
//		// 更新界面表格的用户名字段
//		updateUserName(qqNumVO.getIndex(), nick);
//
//		QQNumVO tempQQ = Constant.QQ_LIST.get(qqNumVO.getQqNum());
//		tempQQ.setHttpClient(httpclient);
//		tempQQ.setPsessionid(psessionid);
//		Constant.QQ_LIST.remove(tempQQ.getQqNum());
//		Constant.QQ_LIST.put(tempQQ.getQqNum(), tempQQ);

		Constant.ALREADY_LOGIN_QUEEN.add(qqNumVO);

		updateAlreadyLogin(Integer.toString(Constant.ALREADY_LOGIN_QUEEN.size()));
	}

	/**
	 * 
	 * 方法概述：退出登录队列
	 * 描述：退出登录队列
	 * 
	 * @param qqnum
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-12
	 */
	public void addLogoutQueen(String qqnum, String status) {

		boolean isExist = false;

		for (QQNumVO qqInQueen : Constant.LOGOUT_QUEEN) {// 判断选择的QQ是否已存在于队列中
			if (qqInQueen.getQqNum().equals(qqnum)) {
				isExist = true;
				break;
			}
		}

		if (!isExist) {
			QQNumVO qq = Constant.QQ_LIST.get(qqnum);
			qq.setLogoutReson(status);

			Constant.QQ_LIST.remove(qqnum);
			Constant.QQ_LIST.put(qqnum, qq);

			Constant.LOGOUT_QUEEN.add(Constant.QQ_LIST.get(qqnum));
		}
	}

	/**
	 * 
	 * 方法概述：退出登录 
	 * 描述：退出登录
	 * 
	 * @param qqnum
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-12
	 */
	public void logout(String qqnum, String status) {
		log.debug(qqnum + "退出登录");

		QQNumVO qq = Constant.QQ_LIST.get(qqnum);
		
		//创建新任务
		LogoutTask task = new LogoutTask(qq,gui,status);
		//添加新任务到线程池中
		Constant.THREAD_POOL_MANAGER.addLogoutTask(task);
		
		Constant.THREAD_POOL_MANAGER.getInfo();
	}

	/**
	 * 
	 * 方法概述：修改昵称 
	 * 描述：修改昵称
	 * 
	 * @param qqnum
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-12
	 */
	public String modifyNick(QQNumVO qq,String nick) {
		log.debug("修改" + qq.getQqNum() + "昵称为" + nick);

		HttpClient httpclient = qq.getHttpClient();

		HttpPost httppost = new HttpPost("http://s.web2.qq.com/api/modify_my_details2");

		// 设置http头信息
		httppost.setHeader("Accept", "*/*");
		httppost.setHeader("Accept-Encoding", "gzip, deflate");
		httppost.setHeader("Accept-Language", "zh-cn");
		httppost.setHeader("Connection", "Keep-Alive");
		httppost.setHeader("Cache-Control", "no-cache");
		httppost.setHeader("Content-Type",
				"application/x-www-form-urlencoded");
		httppost.setHeader("Host", "s.web2.qq.com");
		httppost.setHeader("Referer",
				"http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=3");
		httppost.setHeader("User-Agent",
				"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");

		log.debug("原来的用户资料是：" + qq.getUserinfoJson());

		JSONObject userinfoObj = JSONObject
				.fromObject(qq.getUserinfoJson()); // 由JSON转成JSONOBJECT对象
		JSONObject resultForJson = JSONObject.fromObject(userinfoObj
				.get("result")); // 获取result部份

		StringBuffer jsonString = new StringBuffer();
		
		jsonString.append("{");
		jsonString.append("\"nick\":\"" + toEncodedUnicode(nick,true) + "\",");
		jsonString.append("\"gender\":\"" + resultForJson.get("gender").toString() + "\",");
		jsonString.append("\"shengxiao\":\"" + resultForJson.get("shengxiao").toString() + "\",");
		jsonString.append("\"constel\":\"" + resultForJson.get("constel").toString() + "\",");
		jsonString.append("\"blood\":\"" + resultForJson.get("blood").toString() + "\",");
		jsonString.append("\"birthyear\":\"" + JSONObject.fromObject(resultForJson.get("birthday")).get("year").toString() + "\",");
		jsonString.append("\"birthmonth\":\"" + JSONObject.fromObject(resultForJson.get("birthday")).get("month").toString() + "\",");
		jsonString.append("\"birthday\":\"" + JSONObject.fromObject(resultForJson.get("birthday")).get("day").toString() + "\",");
		jsonString.append("\"phone\":\"\",");
		jsonString.append("\"mobile\":\"\",");
		jsonString.append("\"email\":\"\",");
		jsonString.append("\"occupation\":\"\",");
		jsonString.append("\"college\":\"\",");
		jsonString.append("\"homepage\":\"\",");
		jsonString.append("\"personal\":\"\",");
		jsonString.append("\"vfwebqq\":\"" + qq.getVfwebqq().toString() + "\"}");
		
		log.debug("修改后的昵称是：" + jsonString.toString());

		
		try {
			StringEntity stringEntity = new StringEntity("r=" + jsonString.toString());
			stringEntity.setContentType("application/x-www-form-urlencoded");
			
			log.debug(EntityUtils.toString(stringEntity));

			httppost.setEntity(stringEntity);

			HttpResponse response = httpclient.execute(httppost);

			// 获取响应实
			HttpEntity entity = response.getEntity();

			String responseString = EntityUtils.toString(entity);
			
			log.debug(responseString);
			
			return responseString;
			
		} catch (IOException e) {
			log.error("网络连接超时", e);
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 
	 * 方法概述：修改个性签名
	 * 描述：修改个性签名
	 * @param qqnum
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-12
	 */
	public String modifySingleLongNick(QQNumVO qq,String singleLongNick) {
		log.debug("修改" + qq.getQqNum() + "个性签名为" + singleLongNick);

		HttpClient httpclient = qq.getHttpClient();

		HttpPost httppost = new HttpPost("http://s.web2.qq.com/api/set_long_nick2");

		// 设置http头信息
		httppost.setHeader("Accept", "*/*");
		httppost.setHeader("Accept-Encoding", "gzip, deflate");
		httppost.setHeader("Accept-Language", "zh-cn");
		httppost.setHeader("Connection", "Keep-Alive");
		httppost.setHeader("Cache-Control", "no-cache");
		httppost.setHeader("Content-Type",
				"application/x-www-form-urlencoded");
		httppost.setHeader("Host", "s.web2.qq.com");
		httppost.setHeader("Referer",
				"http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=3");
		httppost.setHeader("User-Agent",
				"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");

		StringBuffer jsonString = new StringBuffer();
		
		jsonString.append("{");
		jsonString.append("\"nlk\":\"" + toEncodedUnicode(singleLongNick,true) + "\",");
		jsonString.append("\"vfwebqq\":\"" + qq.getVfwebqq().toString() + "\"}");
		
		log.debug("修改后的个性签名是：" + jsonString.toString());

		
		try {
			StringEntity stringEntity = new StringEntity("r=" + jsonString.toString());
			stringEntity.setContentType("application/x-www-form-urlencoded");
			
			log.debug(EntityUtils.toString(stringEntity));

			httppost.setEntity(stringEntity);

			HttpResponse response = httpclient.execute(httppost);

			// 获取响应实
			HttpEntity entity = response.getEntity();

			String responseString = EntityUtils.toString(entity);
			
			log.debug(responseString);
			
			return responseString;
			
		} catch (IOException e) {
			log.error("网络连接超时", e);
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 
	 * 方法概述：修改昵称和个性签名
	 * 描述：修改昵称和个性签名
	 * @param nick
	 * @param singleLongNick
	 * 返回类型：void
	 * 修改人：梁铭显
	 * 修改时间：2012-9-20
	 */
	public void modifyNickAndSingleLongNick(String nick,String singleLongNick,List<String> qqNums){
		Iterator<String> i = qqNums.iterator();
		List<QQNumVO> waitModifyNicks = new ArrayList<QQNumVO>();
		
		//过滤未登录的QQ
		while(i.hasNext()){
			String qqNum = i.next();
			
			for (QQNumVO qq : Constant.ALREADY_LOGIN_QUEEN) {
				if(qq.getQqNum().equals(qqNum)){
					waitModifyNicks.add(qq);
					break;
				}
			}
		}
		
		if(!qqNums.isEmpty()){ //修改用户选择的QQ昵称
			if(!"".equals(nick) && "".equals(singleLongNick)){ //只修改昵称
				for (QQNumVO qq : waitModifyNicks) {
					
					setSelectItem(qq.getIndex());
					
					String responseString = modifyNick(qq,nick);
					
					if(responseString == null){
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "网络连接超时");
						return;
					}
					
					if(responseString.contains("\"retcode\":0")){
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "修改昵称成功");
						updateUserName(qq.getIndex(),qq.getQqNum(), nick);
					} else {
//						JSONObject responseForJson = JSONObject.fromObject(responseString);
//						updateOptStatus(qq.getIndex(), responseForJson.getString("tips").toString());
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "修改昵称失败");
					}
				}
			} else if("".equals(nick) && !"".equals(singleLongNick)){ //只修改个性签名
				for (QQNumVO qq : waitModifyNicks) {
					
					setSelectItem(qq.getIndex());
					
					String responseString = modifySingleLongNick(qq,singleLongNick);
					
					if(responseString == null){
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "网络连接超时");
						return;
					}
					
					if(responseString.contains("\"retcode\":0")){
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "修改个性签名成功");
					} else {
//						JSONObject responseForJson = JSONObject.fromObject(responseString);
//						updateOptStatus(qq.getIndex(), responseForJson.getString("tips").toString());
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "修改个性签名失败");
					}
				}
			} else { //修改昵称和个性签名
				for (QQNumVO qq : waitModifyNicks) {
					
					setSelectItem(qq.getIndex());
					
					String nickResponse = modifyNick(qq,nick);
					
					if(nickResponse == null){
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "网络连接超时");
						return;
					}
					
					String singleLongNickResponse = modifySingleLongNick(qq,singleLongNick);
					
					if(singleLongNickResponse == null){
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "网络连接超时");
						return;
					}
					
					if(nickResponse.contains("\"retcode\":0") && singleLongNickResponse.contains("\"retcode\":0")){
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "修改昵称和个性签名成功");
						updateUserName(qq.getIndex(),qq.getQqNum(), nick);
					} else if(!nickResponse.contains("\"retcode\":0") && singleLongNickResponse.contains("\"retcode\":0")){ //修改昵称失败
//						JSONObject nickForJson = JSONObject.fromObject(nickResponse);
//						updateOptStatus(qq.getIndex(), nickForJson.getString("tips").toString());
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "修改昵称失败");
					} else if(nickResponse.contains("\"retcode\":0") && !singleLongNickResponse.contains("\"retcode\":0")){ //修改个性签名失败
//						JSONObject slnForJson = JSONObject.fromObject(singleLongNickResponse);
//						updateOptStatus(qq.getIndex(), slnForJson.getString("tips").toString());
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "修改个性签名失败");
					} else { // 修改昵称和个性签名都失败
//						JSONObject nickForJson = JSONObject.fromObject(nickResponse);
//						JSONObject slnForJson = JSONObject.fromObject(singleLongNickResponse);
//						updateOptStatus(qq.getIndex(), nickForJson.getString("tips").toString() +
//								";" + slnForJson.getString("tips").toString());
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "修改昵称和个性签名失败");
					}
				}
			}
		} else { //修改全部昵称和个性签名
			if(!"".equals(nick) && "".equals(singleLongNick)){ //只修改昵称
				for (QQNumVO qq : Constant.ALREADY_LOGIN_QUEEN) {
					setSelectItem(qq.getIndex());
					
					String responseString = modifyNick(qq,nick);
					
					if(responseString == null){
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "网络连接超时");
						return;
					}
					
					if(responseString.contains("\"retcode\":0")){
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "修改昵称成功");
						updateUserName(qq.getIndex(),qq.getQqNum(), nick);
					} else {
//						JSONObject responseForJson = JSONObject.fromObject(responseString);
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "修改昵称失败");
					}
				}
			} else if("".equals(nick) && !"".equals(singleLongNick)){ //只修改个性签名
				for (QQNumVO qq : Constant.ALREADY_LOGIN_QUEEN) {
					setSelectItem(qq.getIndex());
					
					String responseString = modifySingleLongNick(qq,singleLongNick);
					
					if(responseString == null){
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "网络连接超时");
						return;
					}
					
					if(responseString.contains("\"retcode\":0")){
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "修改个性签名成功");
					} else {
//						JSONObject responseForJson = JSONObject.fromObject(responseString);
						updateOptStatus(qq.getIndex(),qq.getQqNum(),"修改个性签名失败");
					}
				}
			} else { //修改昵称和个性签名
				for (QQNumVO qq : Constant.ALREADY_LOGIN_QUEEN) {
					setSelectItem(qq.getIndex());
					
					String nickResponse = modifyNick(qq,nick);
					
					if(nickResponse == null){
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "网络连接超时");
						return;
					}
					
					String singleLongNickResponse = modifySingleLongNick(qq,singleLongNick);
					
					if(singleLongNickResponse == null){
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "网络连接超时");
						return;
					}
					
					if(nickResponse.contains("\"retcode\":0") && singleLongNickResponse.contains("\"retcode\":0")){
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "修改昵称和个性签名成功");
						updateUserName(qq.getIndex(),qq.getQqNum(), nick);
					} else if(!nickResponse.contains("\"retcode\":0") && singleLongNickResponse.contains("\"retcode\":0")){ //修改昵称失败
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "修改昵称失败");
					} else if(nickResponse.contains("\"retcode\":0") && !singleLongNickResponse.contains("\"retcode\":0")){ //修改个性签名失败
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "修改个性签名失败");
					} else { // 修改昵称和个性签名都失败
//						JSONObject nickForJson = JSONObject.fromObject(nickResponse);
//						JSONObject slnForJson = JSONObject.fromObject(singleLongNickResponse);
						updateOptStatus(qq.getIndex(),qq.getQqNum(), "修改昵称和个性签名失败");
					}
				}
			}
		}
	}

	/**
	 * 
	 * 方法概述：获取时间戳 
	 * 描述：获取时间戳
	 * 
	 * @return 
	 * 返回类型：long 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-10
	 */
	public long getUTCTime() {
		return System.currentTimeMillis();
	}

	/**
	 * 
	 * 方法概述：把汉字转成UNICODE编码
	 * 描述：把汉字转成UNICODE编码
	 * @param theString
	 * @param escapeSpace
	 * @return
	 * 返回类型：String
	 * 修改人：梁铭显
	 * 修改时间：2012-9-19
	 */
	public String toEncodedUnicode(String theString, boolean escapeSpace) {

		int len = theString.length();

		int bufLen = len * 2;

		if (bufLen < 0) {
			bufLen = Integer.MAX_VALUE;
		}

		StringBuffer outBuffer = new StringBuffer(bufLen);

		for (int x = 0; x < len; x++) {
			char aChar = theString.charAt(x);
			
			if ((aChar > 61) && (aChar < 127)) {
				if (aChar == '\\') {
					outBuffer.append('\\');
					outBuffer.append('\\');
					continue;
				}
				outBuffer.append(aChar);
				continue;
			}

			switch (aChar) {
			case ' ':

				if (x == 0 || escapeSpace)
					outBuffer.append('\\');
				outBuffer.append(' ');
				break;
			case '\t':
				outBuffer.append('\\');
				outBuffer.append('t');
				break;
			case '\n':
				outBuffer.append('\\');
				outBuffer.append('n');
				break;
			case '\r':
				outBuffer.append('\\');
				outBuffer.append('r');
				break;
			case '\f':
				outBuffer.append('\\');
				outBuffer.append('f');
				break;
			case '=': // Fall through
			case ':': // Fall through
			case '#': // Fall through
			case '!':
				outBuffer.append('\\');
				outBuffer.append(aChar);
				break;
			default:
				if ((aChar < 0x0020) || (aChar > 0x007e)) {
					// 每个unicode有16位，每四位对应的16进制从高位保存到低位
					outBuffer.append('\\');
					outBuffer.append('u');
					outBuffer.append(toHex((aChar >> 12) & 0xF));
					outBuffer.append(toHex((aChar >> 8) & 0xF));
					outBuffer.append(toHex((aChar >> 4) & 0xF));
					outBuffer.append(toHex(aChar & 0xF));
				} else {
					outBuffer.append(aChar);
				}
			}
		}
		return outBuffer.toString();
	}

	private char toHex(int nibble) {
		char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A','B', 'C', 'D', 'E', 'F' };
		return hexDigit[(nibble & 0xF)];

	}

	/**
	 * 
	 * 方法概述：获取QQ用户名 
	 * 描述：获取QQ用户名
	 * 
	 * @param response
	 * @return 
	 * 返回类型：String 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-10
	 */
	public String getUserName(String response) {
		String userName = response.split(",")[5].replace("'", "").replace(");",
				"");
		return userName;
	}

	/**
	 * 
	 * 方法概述：更新界面 描述：
	 * 
	 * @param qqVoList
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-6
	 */
	public void updateStatus(final int index, final String num, final String status) {
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.updateStatus(index,num, status);
			}
		});
	}
	
	/**
	 * 
	 * 方法概述：更新操作状态
	 * 描述：更新操作状态
	 * @param index
	 * @param status
	 * 返回类型：void
	 * 修改人：梁铭显
	 * 修改时间：2012-9-8
	 */
	public void updateOptStatus(final int index, final String num, final String status){
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.updateOptStatus(index, num, status);
			}
		});
	}

	/**
	 * 
	 * 方法概述：更新界面表格的用户名字段 
	 * 描述：更新界面表格的用户名字段
	 * 
	 * @param index
	 * @param userName
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-10
	 */
	public void updateUserName(final int index, final String num, final String userName) {
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.updateUserName(index, num, userName);
			}
		});
	}

	/**
	 * 
	 * 方法概述：更新挂机时间 
	 * 描述：更新挂机时间
	 * 
	 * @param index
	 * @param loginTime
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-11
	 */
	public void updateLoginTime(final int index, final String loginTime,final String num, final long time) {
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.updateLoginTime(index, loginTime,num,time);
			}
		});
	}

	/**
	 * 
	 * 方法概述：更新表格中的等级信息 
	 * 描述：更新表格中的等级信息
	 * 
	 * @param index
	 * @param level
	 * @param days
	 * @param remainDays
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-10
	 */
	public void updateLevelInfo(final int index, final String num, final String level,
			final String days, final String remainDays) {
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.updateLevelInfo(index, num, level, days, remainDays);
			}
		});
	}

	/**
	 * 
	 * 方法概述：打开验证码输入框 
	 * 描述：打开验证码输入框
	 * 
	 * @param qqNum
	 * @param imageData
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-10
	 */
	public void showVerifyCode(final String qqNum, final ImageData imageData) {
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.showVerifyCode(qqNum, imageData);
			}
		});
	}

	/**
	 * 
	 * 方法概述：提示信息对话框 
	 * 描述：提示信息对话框
	 * 
	 * @param info
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-12
	 */
	public void alert(final String info) {
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.alert(info);
			}
		});
	}

	/**
	 * 
	 * 方法概述：更新已登录个数 
	 * 描述：更新已登录个数
	 * 
	 * @param count
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-14
	 */
	public void updateAlreadyLogin(final String count) {
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.updateAlreadyLogin(count);
			}
		});
	}

	/**
	 * 
	 * 方法概述：更新密码错误个数 
	 * 描述：更新密码错误个数
	 * 
	 * @param count
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-14
	 */
	public void updateWrongPassword() {
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.updateWrongPassword();
			}
		});
	}

	/**
	 * 
	 * 方法概述：设置指定的行为选择状态 
	 * 描述：设置指定的行为选择状态
	 * 
	 * @param index
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-19
	 */
	public void setSelectItem(final int index) {
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.setSelectItem(index);
			}
		});
	}

	/**
	 * 
	 * 方法概述：更新登录失败的个数 
	 * 描述：更新登录失败的个数
	 * 
	 * @param count
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-14
	 */
	public void updateFailCount() {
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.updateFailCount();
			}
		});
	}

	/**
	 * 
	 * 方法概述：更新已等待登录个数 
	 * 描述：更新已等待登录个数
	 * 
	 * @param count
	 * 返回类型：void 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-14
	 */
	public void updateWaitingLogin(final String count) {
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.updateWaitingLogin(count);
			}
		});
	}

	/**
	 * 
	 * 方法概述：将毫秒数换算成x时x分x秒 
	 * 描述：将毫秒数换算成x时x分x秒
	 * 
	 * @param ms
	 * @return 
	 * 返回类型：String 
	 * 修改人：梁铭显 
	 * 修改时间：2012-9-11
	 */
	public String format(long ms) {// 将毫秒数换算成x时x分x秒
		int ss = 1000;
		int mi = ss * 60;
		int hh = mi * 60;
		int dd = hh * 24;

		long day = ms / dd;
		long hour = (ms - day * dd) / hh;
		long minute = (ms - day * dd - hour * hh) / mi;
		long second = (ms - day * dd - hour * hh - minute * mi) / ss;

		String strHour = hour < 10 ? "0" + hour : "" + hour;
		String strMinute = minute < 10 ? "0" + minute : "" + minute;
		String strSecond = second < 10 ? "0" + second : "" + second;

		return strHour + ":" + strMinute + ":" + strSecond;
	}
	
	/**
	 * 重写X509TrustManager，在使用https访问时不认证证书
	 */
	private static X509TrustManager trustManager= new X509TrustManager() {
		@Override
		public void checkClientTrusted(X509Certificate[] arg0, String arg1)
				throws CertificateException {
			
		}

		@Override
		public void checkServerTrusted(X509Certificate[] arg0, String arg1)
				throws CertificateException {
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	};

	public static void main(String[] args) {
//		String test = "ptuiCB('0','0','https://ssl.ptlogin2.qq.com/pt4_302?u1=http%3A//ptlogin4.web2.qq.com/check_sig%3Fpttype%3D1%26uin%3D4841030%26service%3Dlogin%26nodirect%3D0%26ptsig%3DxyYGKsSkZkcbtTIh1UgFiLHDBIWqsmtcxX*gFpkhAXY_%26s_url%3Dhttp%253a%252f%252fweb2.qq.com%252floginproxy.html%253flogin2qq%253d1%2526webqq%255ftype%253d10%26f_url%3D%26ptlang%3D2052%26ptredirect%3D100%26aid%3D1003903%26daid%3D164%26j_later%3D0%26low_login_hour%3D0%26regmaster%3D0','0','登录成功！', '人如若河');";
//		String url = test.split(",")[2].replace("'", "");
//		System.out.println(URLDecoder.decode(url));
//		String test1 = "occupation%22%3A%22%5Cu73AF%5Cu5883%5Cu827A%5Cu672F%5Cu5DE5%5Cu4F5C%5Cu8005%22%2C%22";
//		System.out.println(URLDecoder.decode(test));
//		System.out.println(URLDecoder.decode(test1));
	}
}
